package com.ruoyi.quartz.task;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.enums.AccountOpType;
import com.ruoyi.business.service.*;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component("orderCheckTask")
public class OrderCheckTask {

    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ISysConfigService sysConfigService;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    // 上次发送告警邮件时间
    private volatile Long lastSendAlarmMailsMills = 0L;
    // 上次检查初始化错误订单时间
    private volatile Long lastCheckInitErrOrderTime = 0L;

    @Resource
    private ITRecipientInfoService userRecipientService;

    @Autowired
    private ITSmjGoodListService itSmjGoodListService;

    @Resource
    private ITAccountInfoService accountInfoService;

    @Resource
    private ITAccountLogService accountLogService;

    @Resource
    public CommonService commonService;

    @Resource
    private ITPayChannelService payChannelService;

    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    public void checkTimeout()  {

        logger.info("订单超时检查和处理..");

        orderService.updateAllTimeout();

        SimpleDateFormat sdf  = new SimpleDateFormat("YYYY-mm-dd");
        //修改竖款账号状态

        TOrderInfo tOrderInfo = new TOrderInfo();
//        tOrderInfo.setChannelType("alipay");
//        tOrderInfo.setChannel("smj_sm");
        tOrderInfo.setStatus(3);
        String newdateTime = DateUtils.dealDate("10分钟前");
//        String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        tOrderInfo.getParams().put("beginCreateTime",newdateTime);
//        tOrderInfo.getParams().put("endCreateTime",dateTime);
        List<TOrderInfo> tOrderInfoList = orderService.selectTOrderInfoListByNoAuth(tOrderInfo);
        logger.info("订单关闭时查询超时订单数量：{}",tOrderInfoList.size());
        for (TOrderInfo orderInfo : tOrderInfoList) {
            TRecipientInfo tRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
            TPayChannel payChannel =  payChannelService.selectTPayChannelByCode(orderInfo.getChannel());

            if(orderInfo.getChannel().contains("smj_sm")){
                if( StringUtils.isBlank(orderInfo.getQrcodeContent()) || StringUtils.isBlank(orderInfo.getQrcodeTxt()) ){
                    continue;
                }
                TSmjGoodList tSmjGoodList =  itSmjGoodListService.selectTSmjGoodListById(Long.valueOf(orderInfo.getQrcodeTxt()));
                if(tSmjGoodList==null){
                    continue;
                }
                TOrderInfo queryPaymentOrder = new TOrderInfo();
                queryPaymentOrder.setQrcodeTxt(orderInfo.getQrcodeTxt());
                queryPaymentOrder.setQrcodeContent(orderInfo.getQrcodeContent());
                queryPaymentOrder.setRecipientId(orderInfo.getRecipientId());
                queryPaymentOrder.setChannel(orderInfo.getChannel());
                queryPaymentOrder.setStatus(1);
                List<TOrderInfo> list = orderService.selectTOrderInfoListByNoAuth(queryPaymentOrder);
                logger.info("是否还在被使用{}",list.size());
                if(list.size()>0){
                    continue;
                }
                tSmjGoodList.setGoodStatus(0);
                itSmjGoodListService.updateTSmjGoodList(tSmjGoodList);
            }else if(orderInfo.getChannel().contains("wechat_skd_scan")){
                if(orderInfo.getQrcodeTime()!=null){
                    continue;
                }
                //关闭收款单
                String regionCode = "";
                if (StringUtils.isNotBlank(tRecipientInfo.getCity())) {
                    regionCode = tRecipientInfo.getCity();
                } else if (StringUtils.isNotBlank(tRecipientInfo.getProvince())) {
                    regionCode = tRecipientInfo.getProvince();
                }
                JSONObject proxyObj = new JSONObject();
                if (com.ruoyi.common.utils.StringUtils.isNotBlank(regionCode)) {
                    proxyObj = commonService.getPoxyIp(regionCode);
                }
                String accountJson = tRecipientInfo.getAccountJson();
                JSONObject  accountObj = JSONObject.parseObject(accountJson);
                String ck = accountObj.getString("ck");
                String sid = accountObj.getString("sid");
                String miniprogram_version =accountObj.getString("miniprogram_version");
                String account_id = accountObj.getString("account_id");
                String account_type = accountObj.getString("account_type");
                String closeUrl="https://payapp.wechatpay.cn/receiptwxmgr/receipt/close?miniprogram_version="+miniprogram_version+"&receipt_id="+orderInfo.getQrcodeTxt()+"&account_id="+account_id+"&account_type="+account_type+"&sid="+sid;
                HttpResponse accountResponse = null;
                HashMap<String, String> headerMap = new HashMap();
                headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.53(0x18003531) NetType/4G Language/zh_CN");
                headerMap.put("Connection","keep-alive");
                headerMap.put("content-type","application/json");
                headerMap.put("Accept-Encoding","gzip,compress,br,deflate");
                if (StringUtils.isNotBlank(regionCode)) {
                    accountResponse = HttpUtils.httpFormGet(closeUrl,headerMap,"","",proxyObj.getString("ip") + ":" + proxyObj.getString("prot"));
                }else{
                    accountResponse = HttpUtils.httpFormGet(closeUrl,headerMap,"","","");
                }
                logger.info("关闭微信收款单返回：{}",accountResponse.getBody());
                JSONObject jsonObject = JSONObject.parseObject(accountResponse.getBody());
                if(jsonObject.getIntValue("")==0){
                    orderInfo.setQrcodeTime(new Date());
                    orderService.updateTOrderInfo(orderInfo);
                }
            }
            //退还预扣
            if(payChannel.getReqType()==1){
                TAccountLog queryaccountLog = new TAccountLog();
                queryaccountLog.setBizId(orderInfo.getId());
                queryaccountLog.setUserId(tRecipientInfo.getUserId());
                queryaccountLog.setOpType(AccountOpType.INCOME_ORDER_REVERSAL.getVal());
                List<TAccountLog> accountLogList =  accountLogService.selectTAccountLogListByNoAuth(queryaccountLog);
                if(accountLogList.size()==0){
                    TAccountInfo tAccountInfo = accountInfoService.selectTAccountInfoByUserId(tRecipientInfo.getUserId());
                    long oldbalance = tAccountInfo.getBalance();
                    long balance = tAccountInfo.getBalance()+orderInfo.getMoney();
                    tAccountInfo.setBalance(balance);
                    accountInfoService.updateTAccountInfo(tAccountInfo);
                    //添加账变记录
                    TAccountLog accountLog = new TAccountLog();
                    accountLog.setAccountId(tAccountInfo.getId());
                    accountLog.setUserId(tAccountInfo.getUserId());
                    accountLog.setBizId(orderInfo.getId());
                    accountLog.setOpType(AccountOpType.INCOME_ORDER_REVERSAL.getVal());
                    accountLog.setOpDesc(String.format(AccountOpType.INCOME_ORDER_REVERSAL.getDesc() + "关联订单号【%d】成功增加余额%s元", accountLog.getBizId(),
                            MoneyUtil.fenToYuan(String.valueOf(orderInfo.getMoney()))));
                    // 操作金额。单位分。正数-收入，负数-支出
                    accountLog.setOpAmount(orderInfo.getMoney() * 1);
                    accountLog.setOldAmount(oldbalance);
                    accountLog.setNewAmount(tAccountInfo.getBalance());
                    // 流水
                    accountLogService.insertTAccountLog(accountLog);
                }
            }
        }

    }

    /**
     * 连续5笔不成功关闭收款号
     */
    public void checkSuccess() {

        String limitCountStr = sysConfigService.selectConfigByKey("FAIL_COUNT_LIMIT");
        int limitCount = 0;
        if(StringUtils.isNotBlank(limitCountStr)){
            limitCount = Integer.valueOf(limitCountStr);
        }
        if(limitCount!=0){
            logger.debug("连续几笔不成功关闭收款号.."+limitCount);
            TRecipientInfo recipientInfoParam = new TRecipientInfo();
            recipientInfoParam.setChannelDisabled(0);
            List<TRecipientInfo> recipientInfoResultList = userRecipientService.selectTRecipientInfoList(recipientInfoParam);
            for (TRecipientInfo recipientInfo : recipientInfoResultList) {
                if (recipientInfo.getChannel().equals("alipay_wl_h5")) {
                    String cookies = recipientInfo.getCookie();
                    JSONObject cookieObj = JSONObject.parseObject(cookies);
                    if (StringUtils.isBlank(cookieObj.getString("qrurl"))) {
                        logger.info("收款号【" + recipientInfo.getChannelAccount() + "】未配置码牌,关闭收款账号！");
                        recipientInfo.setChannelDisabled(1);
                        recipientInfo.setDisabledInfo("该收款号未配置码牌");
                        userRecipientService.updateTRecipientInfo(recipientInfo);
                    }
                }
                TOrderInfo queryOrder = new TOrderInfo();
                queryOrder.setRecipientId(recipientInfo.getId());

                int failCount = 0;
//                List<TOrderInfo> lastOrders = orderService.selectTOrderInfoList(queryOrder, limitCount);
//                for (OrderInfo orderInfo : lastOrders) {
//                    if (orderInfo.getPaySucc() != 1) {
//                        failCount++;
//                    } else {
//                        break;
//                    }
//                }
//                if (failCount == 5) {
//                    logger.info("收款号【" + recipientInfo.getChannelAccount() + "】连续5笔未成功,关闭收款账号！");
//                    recipientInfo.setChannelDisabled(1);
//                    recipientInfo.setDisabledInfo("该收款号连续5笔未成功");
//                    userRecipientService.updateById(recipientInfo);
//                }
            }
        }
    }

}
